/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import { LeaderBoard } from "../Models/LeaderBoard.schema";
import { createLeaderBoardDTO, updateLeaderBoardDTO } from "../DTO/LeaderBoard.dto";
import { isExistsforId, isExistsforTitle } from "../hook";
import Axios from "axios";

export class LeaderBoardController {
  constructor(private readonly leaderBoardModel: typeof LeaderBoard) { }
  /**
   * 创建排行榜
   * @param dto 数据传输对象
   * @returns 返回创建对象
   */
  async createItem(dto: createLeaderBoardDTO) {
    try {
      return {
        code: 200,
        message: "创建成功",
        data: await this.leaderBoardModel.create(dto),
      };
    } catch (error) {
      return await error;
    }
  }
  /**
 * 以ID为查找依据删除排行榜
 * @param id 要删除元素的唯一ID
 * @returns
 */
  async removeById(id: string) {
    try {
      if (!await isExistsforId(id, this.leaderBoardModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "删除成功",
          data: await this.leaderBoardModel.deleteOne({ _id: id }),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按ID更新排行榜
   * @param id 要更新的ID
   * @param dto  要更新的内容
   * @returns 更新对象
   */
  async updateById(id: string, dto: updateLeaderBoardDTO) {
    try {
      if (!await isExistsforId(id, this.leaderBoardModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "更新成功",
          data: await this.leaderBoardModel.updateOne({ _id: id }, dto),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
 * 按排行榜名称查找排行榜
 * @param title 要查找的排行榜名称
 * @returns 查询对象
 */
  async getLederBoard() {
    try {
      const data = await Axios.get("http://162.14.104.16:3005/toplist/detail")
      if (data.data)
        return {
          code: 200,
          message: "获取成功",
          data: data.data.list
        }
    }
    catch (error) {
      return await error;
    }
  }

  /**
   * 按ID查找排行榜
   * @param id 要查找的排行榜名称
   * @returns 查询对象
   */
  async findById(id: string) {
    try {
      if (!await isExistsforId(id, this.leaderBoardModel)) {

        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.leaderBoardModel.find({ _id: id }),
        };
      }
    } catch (error) {
      return false;
    }
  }
  //查询全部数据
  async findAll() {
    try {
      if (await this.leaderBoardModel.find().count() != 0)
        return {
          code: 200,
          message: "查询成功",
          data: await this.leaderBoardModel.find(),
        };
      else
        return {
          code: 400,
          message: "该数据集不存在数据"
        }
    }
    catch (error) {
      return await error;
    }
  }
}